import { login, logout, getInfo } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { getStorage, setStorage, removeStorage } from "@/utils/storage";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import $C from "@/utils/socketConfig";
import Chat from "@/utils/chat";

const user = {
  state: {
    token: getToken(),
    name: "",
    nickName: "",
    userId: "",
    deptId: "",
    isUpdate: "",
    isPlatform: "",
    avatar: "",
    roles: [],
    dept: {},
    permissions: [],
    hospital: {},
    userRoles: [],
    affiliatedHospitalFlag: false,

    chat: null,
    chatObj: "", //会话对象
    chatList: [], //会话列表
    chatDetail: [], //会话详情
    totalNoreadnum:0, //未读消息总数角标
    totalPeopleNum:0, //未读人数
    chatBtn:false,
    currentDeptId:null,//当前坐诊门诊

  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_NICKNAME: (state, nickName) => {
      state.nickName = nickName;
    },
    SET_USERID: (state, userId) => {
      state.userId = userId;
    },
    SET_DEPTID: (state, deptId) => {
      state.deptId = deptId;
    },
    SET_USERROLES: (state, userRoles) => {
      state.userRoles = userRoles;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_isUpdate: (state, isUpdate) => {
      state.isUpdate = isUpdate;
    },
    SET_isPlatform: (state, isPlatform) => {
      state.isPlatform = isPlatform;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
    SET_DEPT: (state, dept) => {
      state.dept = dept;
    },
    SET_HOSPITAL: (state, hospital) => {
      state.hospital = hospital;
    },
    SET_affiliatedHospitalFlag: (state, affiliatedHospitalFlag) => {
      state.affiliatedHospitalFlag = affiliatedHospitalFlag;
    },
    SET_CHAT: (state, chat) => {
      state.chat = chat;
    },
    SET_currentDeptId: (state, currentDeptId) => {
      state.currentDeptId = currentDeptId;
    },
    SET_CHATOBJ: (state, chatObj) => {
      state.chatObj = chatObj;
    },
    SET_CHATLIST: (state, list) => {
      state.chatList = list;
    },
    SET_CHATDETAIL: (state, list) => {
      state.chatDetail = list;
    },
    SET_BADGE: (state, num) => {
      state.totalNoreadnum = num;
    },
    SET_CHATBTN: (state, value) => {
      state.chatBtn = value
    },

  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        const data = {
          username,
          password,
          code,
          uuid,
        };
        // encrypt(JSON.stringify(data))
        login(data)
          .then((res) => {
            setToken(res.token);
            commit("SET_TOKEN", res.token);
            resolve();
          })
          .catch((error) => {
            reject(error);
            console.log("Login", error);
          });
      });
    },
    initLogin({ state, dispatch }) {
      const user = JSON.parse(getStorage("user"));
      if (user) {
        state.chat = new Chat({
          url: $C.socketUrl,
        });
        dispatch("getChatList");
        dispatch("updateBadge");
        dispatch("getChatDetail");
      }
    },
    closeSocket({ state }) {
      if (state.chat) {
        state.chat.close();
      }
    },
    getChatList({ state, commit }) {
      // state.chatList = state.chat.getChatList()
      // this.$bus.$on("onUpdateChatList", (list) => {
      //   state.chatList = list
      // })
      commit("SET_CHATLIST", state.chat.getChatList());
    },
    getChatDetail({ state, commit }) {
      // state.chatDetail = state.chat.getChatDetail()
      // this.$bus.$on("onUpdateChatDetail", (list) => {
      //   state.chatDetail = list
      // })
      commit("SET_CHATDETAIL", state.chat.getChatDetail());
    },
    // 初始化总未读数角标
    updateBadge({ state, commit }) {
      // 开启监听总未读数变化
      // this.$bus.$on('totalNoreadnum', (num) => {
      //   state.totalNoreadnum = num
      // })
      state.chat.updateBadge();
    },

    // 获取用户信息
    GetInfo({ commit, state, dispatch }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            // console.log("************获取用户信息")
            const user = res.user;
            const avatar =
              user.avatar == "" || user.avatar == null
                ? require("@/assets/images/profile.jpg")
                : process.env.VUE_APP_BASE_API + user.avatar;
            if (res.roles && res.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              commit("SET_ROLES", res.roles);
              commit("SET_PERMISSIONS", res.permissions);
            } else {
              // alert("当前账号为非医护人员账户，禁止登录电脑端~")
              dispatch("closeSocket");
              removeToken();
              commit("SET_ROLES", ["ROLE_DEFAULT"]);
              reject("当前登录账号为非医护人员账户，禁止登录电脑端~");
            }
            commit("SET_NAME", user.userName);
            commit("SET_NICKNAME", user.nickName);
            commit("SET_USERID", user.userId);
            commit("SET_DEPTID", user.deptId);
            commit("SET_USERROLES", user.roles);
            commit("SET_AVATAR", avatar);
            commit("SET_isUpdate", user.isUpdate);
            commit("SET_isPlatform", user.isPlatform);
            commit("SET_DEPT", user.dept);
            commit("SET_HOSPITAL", res.hospital);
            commit("SET_affiliatedHospitalFlag", res.affiliatedHospitalFlag);
            localStorage.setItem("hospital", JSON.stringify(res.hospital));
            localStorage.setItem("user", JSON.stringify(user));
            dispatch("initLogin");

            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 退出系统
    LogOut({ commit, state, dispatch }) {
      let that = this;
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            dispatch("closeSocket");
            commit("SET_TOKEN", "");
            commit("SET_ROLES", []);
            commit("SET_PERMISSIONS", []);
            commit("SET_isUpdate", "");
            commit("SET_isPlatform", "");
            commit("SET_DEPT", {});
            commit("SET_HOSPITAL", {});
            commit("SET_affiliatedHospitalFlag", false);
            commit("SET_CHAT", null);
            commit("SET_CHATOBJ", {});
            localStorage.removeItem("hospital");
            localStorage.removeItem("user");
            removeToken();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit("SET_TOKEN", "");
        commit("SET_affiliatedHospitalFlag", false);
        localStorage.removeItem("hospital");
        removeToken();
        resolve();
      });
    },
  },
};

export default user;
